package com.dearbinge.opentapi.content.commodity;


import com.baomidou.mybatisplus.plugins.Page;
import com.dearbinge.data.api.commodity.CommodityMessageService;
import com.dearbinge.data.api.moments.BusinessCircleService;
import com.dearbinge.data.pojo.commodity.vo.CommodityDetailsVO;
import com.dearbinge.data.pojo.commodity.vo.CommodityForwardVO;
import com.dearbinge.data.pojo.commodity.vo.CommodityMessageRequestVO;
import com.dearbinge.data.pojo.commodity.vo.CommodityMessageResponseVO;
import com.dearbinge.data.pojo.commodityspec.vo.CommoditySpecRequestVO;
import com.dearbinge.utils.BeanValidator;
import com.dearbinge.utils.PriceUtils;
import com.dearbinge.utils.ResultMsg;
import com.dearbinge.utils.enums.ResultStatusCodeEnum;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品信息控制层
 *
 * @author wes
 * @date 18:22 2019/1/4
 */
@Api(tags = "2.1、商品-商品信息")
@RestController
@CrossOrigin
@RequestMapping("/commodity")
@EnableAutoConfiguration
public class CommodityMessageController extends WebMvcConfigurerAdapter {


    @Autowired
    private CommodityMessageService commodityMessageService;
    @Autowired
    private BusinessCircleService businessCircleService;

    @ApiOperation(value = "商品发布（id为空||id为0）/修改", notes = "商品发布（id为空||id为0）/修改")
    @RequestMapping(value = "/addOrUpdate", method = RequestMethod.POST)
    public ResultMsg<String> addOrUpdate(@RequestBody CommodityMessageRequestVO commodityMessage) {
        try {
            String commodityType = commodityMessage.getCommodityType();
            if (commodityType != null) {
                if (!isNumeric(commodityType)) {
                    return ResultMsg.error(ResultStatusCodeEnum.CODE500.getCode(), "commodityType商品类目编码为纯数字");
                }
            }
            //对价格验证
            if (!PriceUtils.checkPrice(commodityMessage.getRetailPrice())) {
                return ResultMsg.error(ResultStatusCodeEnum.CODE500.getCode(), "价格输入错误");
            }
            List<CommoditySpecRequestVO> listSpec = commodityMessage.getListSpec();
            if (listSpec ==null) {
                return ResultMsg.error(ResultStatusCodeEnum.CODE5001.getCode(), "规格不能为空");
            }



                //最大价
                BigDecimal max, min;
                max = min = listSpec.get(0).getRetailPrice();
                //校验展示价
                BigDecimal retailPrice = commodityMessage.getRetailPrice();
                for (CommoditySpecRequestVO commoditySpecRequestVO : listSpec) {
                    if (!PriceUtils.checkPrice(commoditySpecRequestVO.getRetailPrice())) {
                        return ResultMsg.error(ResultStatusCodeEnum.CODE500.getCode(), "价格输入错误");
                    }
                    if (commoditySpecRequestVO.getStockCount() == null) {
                        return ResultMsg.error(ResultStatusCodeEnum.CODE500.getCode(), "规格库存不能为空");
                    }
                    if (commoditySpecRequestVO.getSpecificationDesc() == null) {
                        return ResultMsg.error(ResultStatusCodeEnum.CODE500.getCode(), "规格描述不能为空");
                    }
                    BigDecimal price = commoditySpecRequestVO.getRetailPrice();
                    if (retailPrice.compareTo(price) < 0) {
                        // 判断最大值
                        max = price;
                    }
                    if (retailPrice.compareTo(price) > 0) {
                        // 判断最小值
                        min = price;
                    }
                }
                //大于最大 返回错误
                if (retailPrice.compareTo(max) > 0) {
                    return ResultMsg.error(ResultStatusCodeEnum.CODE500.getCode(), "展示价不能大于最大的规格价");
                }
                //小于最小 返回错误
                if (retailPrice.compareTo(min) < 0) {
                    return ResultMsg.error(ResultStatusCodeEnum.CODE500.getCode(), "展示价不能小于最小的规格价");
                }




            Integer dataCode;
            if (commodityMessage.getId() != null && commodityMessage.getId() != 0) {
                dataCode = commodityMessageService.update(commodityMessage);
                if (dataCode > 1) {
                    return ResultMsg.ok("修改成功");
                }
            } else {
                if (listSpec == null) {
                    ResultMsg.error(ResultStatusCodeEnum.CODE500.getCode(), "规格不能为空");
                }
                dataCode = commodityMessageService.insert(commodityMessage);
                if (dataCode > 2) {
                    return ResultMsg.ok("添加成功");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultMsg.error(ResultStatusCodeEnum.CODE500.getCode(), ResultStatusCodeEnum.CODE500.getDesc());
    }


    @ApiOperation(value = "删除商品", notes = "删除商品")
    @ApiImplicitParam(name = "id", value = "主键id", paramType = "query")
    @RequestMapping(value = "/deleteCommodityMessage", method = RequestMethod.GET)
    public ResultMsg<String> deleteCommodityMessage(Integer id) {
        try {
            Integer dataCode = commodityMessageService.deleteCommodityMessage(id);
            if (dataCode > 0) {
                return ResultMsg.ok("删除成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultMsg.error(ResultStatusCodeEnum.CODE500.getCode(), ResultStatusCodeEnum.CODE500.getDesc());
    }


    @ApiOperation(value = "根据商品类目查询商品集", notes = "根据商品类目查询商品集")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryId", value = "类目id,不传查全部", paramType = "query"),
            @ApiImplicitParam(name = "lastId", value = "最新的id", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "页面记录数", paramType = "query")})
    @ApiResponses({
            @ApiResponse(response = CommodityMessageResponseVO.class, code = 200, message = "返回结果参数")
    })
    @RequestMapping(value = "/listCommodityByCategory", method = RequestMethod.GET)
    public ResultMsg<Page> listCommodityByCategory(String categoryId, Integer lastId, Integer current, Integer size) {
        try {
            Page shopGenre = commodityMessageService.listCommodityByCategory(categoryId, lastId, current, size);
            return ResultMsg.okData(shopGenre, ResultStatusCodeEnum.SUCCESS.getDesc());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultMsg.error(ResultStatusCodeEnum.CODE500.getCode(), ResultStatusCodeEnum.CODE500.getDesc());
    }


    @ApiOperation(value = "根据商品id查询商品详情", notes = "根据商品id查询商品详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "commodityId", value = "商品id", paramType = "query", required = true),
            @ApiImplicitParam(name = "userId", value = "当前登录的用户id", paramType = "query", required = true),
            @ApiImplicitParam(name = "otherId", value = "转发商品的用户id（下家）", paramType = "query"),
    })
    @RequestMapping(value = "/getCommodityMessageById", method = RequestMethod.GET)
    public ResultMsg<CommodityDetailsVO> getCommodityMessageById(String userId, String otherId, Integer commodityId) {
        try {
            //校验参数非空
            Map<String, Object> paramMap = new HashMap<String, Object>(16);
            paramMap.put("commodityId", commodityId);
            paramMap.put("userId", userId);
            Map<String, Object> checkParam = BeanValidator.checkParam(paramMap);
            if (!(boolean) checkParam.get(BeanValidator.FLAG)) {
                return ResultMsg.error(ResultStatusCodeEnum.CODE5001.getCode(), checkParam.get("name") + "参数为空");
            }
            return commodityMessageService.getCommodityMessageById(userId, otherId, commodityId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultMsg.error(ResultStatusCodeEnum.CODE500.getCode(), ResultStatusCodeEnum.CODE500.getDesc());
    }


    @ApiOperation(value = "用户能否发商品", notes = "用户能否发商品")
    @ApiImplicitParam(name = "userId", value = "用户id", paramType = "query")
    @RequestMapping(value = "/checkAddCommodityStatus", method = RequestMethod.GET)
    public ResultMsg<Boolean> checkAddCommodityStatus(String userId) {
        try {
            return commodityMessageService.checkAddCommodityStatus(userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultMsg.error(ResultStatusCodeEnum.CODE500.getCode(), ResultStatusCodeEnum.CODE500.getDesc());
    }

    @ApiOperation(value = "查询上下架商品", notes = "查询上下架商品")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", paramType = "query", required = true),
            @ApiImplicitParam(name = "commodityStatus", value = "商品状态 （0下架 1上架） 不传查全部", paramType = "query"),
            @ApiImplicitParam(name = "current", value = "当前页", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "页面记录数", paramType = "query")})
    @ApiResponses({
            @ApiResponse(response = CommodityMessageResponseVO.class, code = 200, message = "返回结果参数")
    })
    @RequestMapping(value = "/listByCommodityStatus", method = RequestMethod.GET)
    public ResultMsg<Page> listByCommodityStatus(String userId, Boolean commodityStatus, Integer current, Integer size) {
        try {
            Page page = commodityMessageService.listByCommodityStatus(userId, commodityStatus, current, size);
            return ResultMsg.ok(page);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultMsg.error(ResultStatusCodeEnum.CODE500.getCode(), ResultStatusCodeEnum.CODE500.getDesc());
    }




    @ApiOperation(value = "修改商品上下架", notes = "修改商品上下架")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "commodityId", value = "商品id", paramType = "query", required = true),
            @ApiImplicitParam(name = "commodityStatus", value = "商品状态 （0下架 1上架）", paramType = "query", required = true)})
    @RequestMapping(value = "/updateCommodityStatus", method = RequestMethod.GET)
    public ResultMsg<String> updateCommodityStatus(Integer commodityId, Boolean commodityStatus) {
        try {
            Integer dataCode = commodityMessageService.updateCommodityStatus(commodityId, commodityStatus);
            if (dataCode > 0) {
                return ResultMsg.ok("修改成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultMsg.error(ResultStatusCodeEnum.CODE500.getCode(), ResultStatusCodeEnum.CODE500.getDesc());
    }


    @ApiOperation(value = "查询分销商品列表", notes = "查询分销商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "shopId", value = "店铺id", paramType = "query", required = true),
            @ApiImplicitParam(name = "current", value = "当前页", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "页面记录数", paramType = "query")})
    @ApiResponses({
            @ApiResponse(response = CommodityForwardVO.class, code = 200, message = "返回结果参数")
    })
    @RequestMapping(value = "/listForwardCommodity", method = RequestMethod.GET)
    public ResultMsg<Page> listForwardCommodity(Integer shopId, Integer current, Integer size) {
        try {
            Page page = commodityMessageService.listForwardCommodity(shopId, current, size);
            return ResultMsg.ok(page);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultMsg.error(ResultStatusCodeEnum.CODE500.getCode(), ResultStatusCodeEnum.CODE500.getDesc());
    }


    @ApiOperation(value = "数据回响 修改商品", notes = "数据回响 修改商品")
    @ApiImplicitParam(name = "commodityId", value = "商品id", paramType = "query", required = true)
    @RequestMapping(value = "/getCommodityResponse", method = RequestMethod.GET)
    public ResultMsg<CommodityMessageRequestVO> getCommodityResponse(Integer commodityId) {
        try {
            CommodityMessageRequestVO commodity = commodityMessageService.getCommodityResponse(commodityId);
            return ResultMsg.okData(commodity, ResultStatusCodeEnum.SUCCESS.getDesc());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultMsg.error(ResultStatusCodeEnum.CODE500.getCode(), ResultStatusCodeEnum.CODE500.getDesc());
    }


    private static boolean isNumeric(String str) {
        try {
            Long.parseLong(str);
            return true;
        } catch (NumberFormatException e) {

            return false;
        }
    }


    /*————————————————————————废弃的接口 新版本上线后删除 只是为了兼容旧版本—————————————————————*/

    @ApiOperation(value = "查询个人商品动态（废弃）", notes = "查询个人商品动态（废弃）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "要看到的用户id", paramType = "query", required = true),
            @ApiImplicitParam(name = "current", value = "当前页", paramType = "query"),
            @ApiImplicitParam(name = "size", value = "页面记录数", paramType = "query")})
    @ApiResponses({
            @ApiResponse(response = CommodityMessageResponseVO.class, code = 200, message = "返回结果参数")
    })
    @RequestMapping(value = "/listCommodityMoments", method = RequestMethod.GET)
    public ResultMsg<Page> listCommodityMoments(String userId, Integer current, Integer size) {
        try {
            Page  page = businessCircleService.listAllMomentsByUserId(userId, current, size, 1);
            return ResultMsg.ok(page);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResultMsg.error(ResultStatusCodeEnum.CODE500.getCode(), ResultStatusCodeEnum.CODE500.getDesc());
    }

}
